<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商品管理</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="../css/common.css">
</head>
<body>
<div class="container">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>商品管理</h2>
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#productModal">
            新增商品
        </button>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
        <div class="row g-3">
            <div class="col-md-4">
                <select id="searchCategoryId" class="form-select">
                    <option value="">全部分类</option>
                </select>
            </div>
            <div class="col-md-4">
                <input type="number" id="searchMinPrice" class="form-control" placeholder="最低价格">
                <input type="number" id="searchMaxPrice" class="form-control mt-2" placeholder="最高价格">
            </div>
            <div class="col-md-4">
                <button class="btn btn-success w-100" onclick="queryProductList(1)">搜索</button>
                <button class="btn btn-light w-100 mt-2" onclick="resetSearch()">重置</button>
            </div>
        </div>
    </div>

    <!-- 商品列表 -->
    <div class="card">
        <div class="card-body">
            <table class="table table-hover table-bordered">
                <thead class="table-primary">
                <tr>
                    <th>商品ID</th>
                    <th>所属分类</th>
                    <th>价格（元）</th>
                    <th>库存数量</th>
                    <th>创建时间</th>
                    <th>更新时间</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody id="productTableBody">
                <tr><td colspan="7" class="text-center">加载中...</td></tr>
                </tbody>
            </table>
        </div>
    </div>

    <!-- 分页 -->
    <div id="pagination-container"></div>
</div>

<!-- 新增/编辑商品弹窗 -->
<div class="modal fade" id="productModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTitle">新增商品</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="productForm">
                    <input type="hidden" id="productId">
                    <div class="mb-3">
                        <label for="categoryId" class="form-label">所属分类 <span class="text-danger">*</span></label>
                        <select class="form-select" id="categoryId" required>
                            <option value="">请选择分类</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="price" class="form-label">价格（元） <span class="text-danger">*</span></label>
                        <input type="number" step="0.01" min="0" class="form-control" id="price" required placeholder="请输入商品价格">
                    </div>
                    <div class="mb-3">
                        <label for="stock" class="form-label">库存数量 <span class="text-danger">*</span></label>
                        <input type="number" min="0" class="form-control" id="stock" required placeholder="请输入库存数量">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="saveProduct()">保存</button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="../js/common.js"></script>
<script>
    let currentPage = 1;
    const pageSize = 10;

    window.onload = function () {
        SelectData.loadCategories("categoryId");
        SelectData.loadCategories("searchCategoryId");
        queryProductList(currentPage);
    };

    // 查询商品列表
    async function queryProductList(pageNum) {
        try {
            const categoryId = document.getElementById("searchCategoryId").value;
            const minPrice = document.getElementById("searchMinPrice").value;
            const maxPrice = document.getElementById("searchMaxPrice").value;

            const res = await axios.get("/api/products/page", {
                params: {
                    pageNum,
                    pageSize,
                    categoryId: categoryId || undefined,
                    minPrice: minPrice || undefined,
                    maxPrice: maxPrice || undefined
                }
            });

            const { records, total } = res.data;
            currentPage = pageNum;
            const tableBody = document.getElementById("productTableBody");
            tableBody.innerHTML = "";

            if (records.length === 0) {
                tableBody.innerHTML = '<tr><td colspan="7" class="text-center">暂无数据</td></tr>';
                return;
            }

            records.forEach(product => {
                const row = `
                        <tr>
                            <td>${product.productId}</td>
                            <td>${product.category?.categoryName || "未知分类"}</td>
                            <td>${product.price.toFixed(2)}</td>
                            <td>${product.stock}</td>
                            <td>${Common.formatDate(product.createTime)}</td>
                            <td>${Common.formatDate(product.updateTime)}</td>
                            <td>
                                <button class="btn btn-sm btn-outline-primary" onclick="editProduct(${product.productId})">编辑</button>
                                <button class="btn btn-sm btn-outline-danger" onclick="deleteProduct(${product.productId})">删除</button>
                                <button class="btn btn-sm btn-outline-warning" onclick="decreaseStock(${product.productId})">扣减库存</button>
                            </td>
                        </tr>
                    `;
                tableBody.innerHTML += row;
            });

            Common.renderPagination(total, pageNum, pageSize, queryProductList);
        } catch (err) {
            Common.errorMsg("查询商品失败：" + err.message);
            document.getElementById("productTableBody").innerHTML = '<tr><td colspan="7" class="text-center">查询失败</td></tr>';
        }
    }

    // 重置搜索
    function resetSearch() {
        document.getElementById("searchCategoryId").value = "";
        document.getElementById("searchMinPrice").value = "";
        document.getElementById("searchMaxPrice").value = "";
        queryProductList(1);
    }

    // 编辑商品
    async function editProduct(productId) {
        try {
            const res = await axios.get(`/api/products/${productId}`);
            const product = res.data;

            document.getElementById("productId").value = product.productId;
            document.getElementById("categoryId").value = product.categoryId;
            document.getElementById("price").value = product.price;
            document.getElementById("stock").value = product.stock;
            document.getElementById("modalTitle").textContent = "编辑商品";

            new bootstrap.Modal(document.getElementById("productModal")).show();
        } catch (err) {
            Common.errorMsg("加载商品信息失败：" + err.message);
        }
    }

    // 保存商品
    async function saveProduct() {
        const categoryId = document.getElementById("categoryId").value;
        const price = document.getElementById("price").value;
        const stock = document.getElementById("stock").value;
        const productId = document.getElementById("productId").value;

        if (!categoryId || !price || !stock) {
            Common.errorMsg("请填写必填字段！");
            return;
        }

        const productData = {
            categoryId: parseInt(categoryId),
            price: parseFloat(price),
            stock: parseInt(stock)
        };

        try {
            if (productId) {
                productData.productId = parseInt(productId);
                await axios.put("/api/products", productData);
                Common.successMsg("编辑商品成功！");
            } else {
                await axios.post("/api/products", productData);
                Common.successMsg("新增商品成功！");
            }

            bootstrap.Modal.getInstance(document.getElementById("productModal")).hide();
            queryProductList(currentPage);
            document.getElementById("productForm").reset();
            document.getElementById("productId").value = "";
            document.getElementById("modalTitle").textContent = "新增商品";
        } catch (err) {
            Common.errorMsg("保存商品失败：" + err.message);
        }
    }

    // 删除商品
    function deleteProduct(productId) {
        Common.confirmMsg("确定要删除该商品吗？", async () => {
            try {
                await axios.delete(`/api/products/${productId}`);
                Common.successMsg("删除商品成功！");
                queryProductList(currentPage);
            } catch (err) {
                Common.errorMsg("删除商品失败：" + err.message);
            }
        });
    }

    // 库存扣减
    async function decreaseStock(productId) {
        const num = prompt("请输入扣减库存数量（需大于0）：", 1);
        if (!num || isNaN(num) || parseInt(num) <= 0) {
            Common.errorMsg("请输入有效的扣减数量！");
            return;
        }

        try {
            await axios.post("/api/products/decrease-stock", {
                productId: productId,
                num: parseInt(num)
            });
            Common.successMsg("库存扣减成功！");
            queryProductList(currentPage);
        } catch (err) {
            Common.errorMsg("库存扣减失败：" + err.message);
        }
    }
</script>
</body>
</html>